import { Article, Channel } from '@/types/data'
import { RootAction } from '@/types/store'

type StateType = {
  userChannels: Channel[]
  allChannels: Channel[]
  active: number
  channelArticles: {
    [key: number]: {
      pre_timestamp: string
      results: Article[]
    }
  }
}

const initValue = {
  userChannels: [],
  allChannels: [],
  active: 0,
  channelArticles: {},
}

export default function homeReducer(
  state: StateType = initValue,
  action: RootAction
) {
  if (action.type === 'home/set_user_channels') {
    return {
      ...state,
      userChannels: action.payload,
    }
  }
  if (action.type === 'home/set_all_channels') {
    return {
      ...state,
      allChannels: action.payload,
    }
  }

  if (action.type === 'home/set_active') {
    return {
      ...state,
      active: action.payload,
    }
  }

  if (action.type === 'home/set_channel_articles') {
    const { pre_timestamp, results, channel_id } = action.payload

    const oldResults = state.channelArticles[channel_id]?.results || []

    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          pre_timestamp: pre_timestamp,
          // 数据应该是追加式的 而不是覆盖式!!
          results: [...oldResults, ...results],
        },
      },
    }
  }

  if (action.type === 'home/refresh_list') {
    const { pre_timestamp, results, channel_id } = action.payload
    return {
      ...state,
      channelArticles: {
        ...state.channelArticles,
        [channel_id]: {
          pre_timestamp: pre_timestamp,
          results: results,
        },
      },
    }
  }

  return state
}
